<template>
  <basic-container>
    <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="form"
               :page="page"
               class="tenant-list"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <!--<template slot-scope="scope" slot="menu">-->
        <!--<el-button type="text"-->
                   <!--icon="el-icon-setting"-->
                   <!--size="small"-->
                   <!--@click="adminSetting(scope.row, scope.index)">管理员设置-->
        <!--</el-button>-->
      <!--</template>-->
      <template slot-scope="{row}" slot="regionId">
        {{row.regionName}}
      </template>
      <template slot-scope="scope" slot="industryForm">
        <el-cascader :options="industryOptions" v-model="industry" @change="handleIndustryChange"></el-cascader>
      </template>
    </avue-crud>
    <!--<el-dialog title="管理员配置"-->
               <!--:visible.sync="box"-->
               <!--width="60%">-->

      <!--<span slot="footer" class="dialog-footer">-->
        <!--<el-button @click="box = false">取 消</el-button>-->
        <!--<el-button type="primary" @click="submit">确 定</el-button>-->
      <!--</span>-->
    <!--</el-dialog>-->
  </basic-container>
</template>
<script>
  import { getList, verifyUnique, add, update, remove } from "@/api/tenant/tenant";
  import { regionTree } from "@/api/organ/region";
  import { mobileRule, emailRule } from '@/util/validate'
  // import { sm4Decrypt } from '@/util/smcrypto'

  export default {
    name: "tenant-info",
    inheritAttrs: false,
    data() {
      const validCode = (rule, value, callback) => {
        let data = {value: value};
        if (this.form.id) {
          data = {value: value, id: this.form.id};
        }
        verifyUnique(data).then(data => {
          if (!data.success)
            callback(new Error('此租户编码已被使用!'));
          else
            callback()
        })
          .catch(err => {
            console.log(err);
            callback(new Error('验证失败!'))
          })
      };
      return {
        form: {
          regionName: '',
          industry1: '',
          industry2: '',
        },
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          tip: false,
          border: true,
          index: true,
          indexLabel: '序号',
          size: 'small',
          columnBtn: false,
          refreshBtn: false,
          menuWidth: 260,
          column: [
            {
              label: "租户编码",
              prop: "code",
              search: true,
              display: false
            },
            {
              label: "租户名称",
              prop: "name",
              search: true,
              display: false
            },
            {
              label: "所属区划",
              prop: "regionId",
              type: "tree",
              dicData: [],
              props: {
                value: 'id',
                label: "title"
              },
              search: true,
              slot: true,
              display: false
            },
          ],
          group: [
            {
              label: "基本信息",
              icon: 'el-icon-chat-square',
              prop: 'groupBasic',
              column: [
                {
                  label: "租户编码",
                  prop: "code",
                  tip: '租户名称拼音首字母组合',
                  rules: [
                    { required: true, message: "请输入租户编码", trigger: "blur" },
                    {min: 1, max: 16, message: '长度在 1 到 16 个字符'},
                    {pattern: /^[A-Za-z0-9_]+$/, message: '只能输入英文、数字或下划线'},
                    { validator: validCode, trigger: 'blur' }
                  ]
                },
                {
                  label: "租户名称",
                  prop: "name",
                  rules: [
                    { required: true, message: "请输入租户名称", trigger: "blur" }
                  ]
                },
                {
                  label: "所属区划",
                  prop: "regionId",
                  type: "tree",
                  dicData: [],
                  props: {
                    value: 'id',
                    label: "title"
                  },
                  rules: [
                    { required: true, message: "请选择所属区划", trigger: "blur" }
                  ]
                },
                {
                  label: "租户简称",
                  prop: "shortName",
                  search: false,
                },
                {
                  label: "所属行业",
                  prop: "industry",
                  search: false,
                  formslot: true
                },
                {
                  label: "域名",
                  prop: "domainName",
                  hide: true
                },
                {
                  label: "租户说明",
                  prop: "remark",
                  type: "textarea",
                  search: false,
                  minWidth: '200',
                  span: 24,
                  minRows: 3
                },
              ]
            },
            {
              label: "联系人信息(联系人即为租户管理员，账号默认为手机号)",
              icon: 'el-icon-edit-outline',
              prop: 'groupContract',
              column: [
                {
                  label: "姓名",
                  prop: "contact",
                  search: false,
                  rules: [
                    { required: true, message: "请输入姓名", trigger: "blur" }
                  ]
                },
                {
                  label: "手机号",
                  prop: "contactMobile",
                  search: false,
                  rules: [
                    { required: true, message: "请输入手机号", trigger: "blur" },
                    { validator: mobileRule, trigger: 'blur' },
                  ]
                },
                {
                  label: "邮箱",
                  prop: "contactEmail",
                  search: false,
                  rules: [
                    { required: true, message: "请输入邮箱", trigger: "blur" },
                    { validator: emailRule, trigger: 'blur' },
                  ]
                },
                {
                  label: "邮政编码",
                  prop: "postal",
                  search: false,
                },
                {
                  label: "联系地址",
                  prop: "address",
                  search: false,
                  span: 24,
                }
              ]
            }
          ]
        },
        data: [],
        industryOptions: [{
          value: '公共管理与社会组织',
          label: '公共管理与社会组织',
          children: [{
            value: '国家机构',
            label: '国家机构'
          }]
        }],
        industry: [],
      }
    },
    created() {
      regionTree().then(res => {
        const data = res.data;
        this.setRegionData("regionId", data);
      });
    },
    methods: {
      onLoad(page, params = {}) {
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          this.industry = [];
          const industry1 = this.form.industry1
          const industry2 = this.form.industry2
          if (industry1 && industry2) {
            this.industry = [industry1, industry2]
          }
        }
        done();
      },
      rowSave(row, loading, done) {
        const load = this.$loading({
          lock: true,
          text: '租户创建中，请稍后......',
          spinner: "el-icon-loading"
        });
        this.form.regionName = this.form.$regionId;
        add(this.form).then(() => {
          loading();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          done();
          console.log(error);
        }).finally(() =>{
          load.close();
        });
      },
      rowUpdate(row, index, loading, done) {
        this.form.regionName = this.form.$regionId;
        update(this.form).then(ret => {
          if (ret.success) {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            done();
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          done();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("租户删除后租户所有用户将不能使用，确定要删除该租户吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row);
          })
          .then(ret => {
            if (ret.success) {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.onLoad(this.page, params);
        done();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      handleIndustryChange(value) {
        if (value) {
          this.form.industry1 = value[0]
          this.form.industry2 = value[1]
        }
      },

      // 赋值区划
      setRegionData(key, res) {
        const index = this.$refs.crud.findColumnIndex("regionId");
        this.option.column[index].dicData = res;
        this.option.group[0].column.forEach((val, idx) => {
          if (val.prop == key) {
            this.option.group[0].column[idx].dicData = res;
          }
        });
      },
    }
  }
</script>
<style scoped lang="scss">
  @import "~_s/placeholders";
  @import "~_s/table-list";

  ::v-deep .tenant-list {
    @extend %fullsize;
    @extend %table-list;
  }
</style>